﻿using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace leapt.Api.Filter
{
    /// <summary>
    /// this class is for swagger to generate AuthToken Header filed on swagger UI
    /// </summary>
    public class AddAuthTokenHeaderParameter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {

            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();

            var attrs = context.ApiDescription.ActionAttributes();
            var contAttrs = context.ApiDescription.ControllerAttributes();

            //foreach (var attr in attrs)
            //{

         
                // 如果 Attribute 是我们自定义的验证过滤器            
                //if (attr.GetType() == typeof(AuthorizeAttribute))
                //{
                //    //HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
                //    operation.Parameters.Add(new NonBodyParameter()
                //    {
                //        Name = "Authorization",
                //        In = "header",
                //        Type = "string",
                //        Required = false
                //    });
                //}

            //}
            var attribute = context.ApiDescription.ActionAttributes().Where(a =>
                a.GetType() == typeof(AllowAnonymousAttribute)).FirstOrDefault();
            if (attribute == null)
            {
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name = "Authorization",
                    In = "header",
                    Type = "string",
                    Required = false
                });
            }
        }
    }
}
